
<template>
  <div>
    <DataTable
      :value="httpStreams"
      v-if="httpStreams.length > 0"
    >
      <Column header="Name">
        <template #body="{ data }">
          {{ data.name }}
        </template>
      </Column>
      <Column header="Configs">
        <template #body="{ data }">
          {{ data.basicConfigs ? data.basicConfigs.length : '' }}
        </template>
      </Column>
      <Column header="#">
        <template #body="{ index }">
          <Button
            severity="secondary"
            @click="editStream(index)"
            variant="text"
            label="Edit"
          ></Button>
          <Button
            severity="danger"
            @click="deleteStream($event, index)"
            variant="text"
            label="Delete"
          ></Button>
        </template>
      </Column>
    </DataTable>
    <div class="flex h-30px items-center justify-center gap-2" v-else>
      <Button icon="pi pi-check" size="small" style="width: 120px" @click="addStreamFn">+ UpStream</Button>
    </div>

    <add-http-stream-dialog
     ref="addHttpStreamDialogRef"
    ></add-http-stream-dialog>
  </div>
</template>
<script setup lang="ts">

// Stream 配置
import { ref, useTemplateRef } from 'vue'
import type { HttpStreamConfig } from '@/types/dt/Dt.ts'
import { useConfirm } from 'primevue/useconfirm'
import AddHttpStreamDialog from '@/views/tools/nginx/detail-comps/add-http-up-stream-dialog.vue'

const confirm = useConfirm()
const addHttpStreamDialogRef = useTemplateRef('addHttpStreamDialogRef')

const httpStreams = ref<HttpStreamConfig[]>([])
function addStreamFn() {
  addHttpStreamDialogRef.value!.open()
    .then(v => {
        httpStreams.value.push(v)
    })
    .catch(e => {
      console.error(e)
    })
}

function editStream(index: number) {
  const stream = httpStreams.value[index]
  addHttpStreamDialogRef.value!.open(stream)
    .then(v => {
      httpStreams.value[index] = v
    })
    .catch(e => {
      console.error(e)
    })
}

function deleteStream(event: MouseEvent, index: number) {
  confirm.require({
    target: event.currentTarget! as HTMLElement,
    message: 'Do you want to delete this record?',
    icon: 'pi pi-exclamation-triangle',
    rejectProps: {
      label: 'Cancel',
      severity: 'secondary',
      outlined: true,
    },
    acceptProps: {
      severity: 'danger',
      label: 'Delete',
    },
    accept: () => {
      httpStreams.value.splice(index, 1)
    },
  })
}
function getConfig() : HttpStreamConfig[] {
  return httpStreams.value
}
function setConfig(config : HttpStreamConfig[]) {
  httpStreams.value = config
}
defineExpose({
  addStream: addStreamFn, getConfig, setConfig
})
</script>

<style scoped>

</style>
